<?php

namespace App\Filament\Resources\Admin\Roles\Pages;

use App\Filament\Resources\Admin\Roles\RoleResource;
use App\Models\Admin\AdminPermission;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Collection;
use Spatie\Permission\Models\Role;

class RolePermission extends Page
{
    use InteractsWithRecord;

    protected static string $resource = RoleResource::class;

    protected string $view = 'filament.resources.admin.role-permission';

    public Collection $permissions;

    public array $selectedPermissions = [];

    public function mount(int|string $id): void
    {
        $this->record = Role::findOrFail($id);
        $this->permissions = AdminPermission::query()
            ->with('children')
            ->where('parent_id', 0)
            ->get();

        $this->selectedPermissions = $this->record->permissions->pluck('id')->toArray();
    }

    public function savePermissions(array $selectedPermissions = []): void
    {
        $permissions = AdminPermission::whereIn('id', $selectedPermissions)
            ->with('children')
            ->get()
            ->map(function ($permission) {
                if ($permission->children->isNotEmpty()) {
                    return null;
                }

                return $permission->name;
            })
            ->filter()
            ->toArray();
        $this->record->syncPermissions($permissions);

        Notification::make()
            ->title('设置成功')
            ->success()
            ->send();
    }

    public function getTitle(): Htmlable|string
    {
        return '';
    }
}
